package com.bincloud.vue.admin.web.util.security.impl;

import com.bincloud.vue.admin.common.exception.BaseException;
import com.bincloud.vue.admin.common.exception.CodeMsg;
import com.bincloud.vue.admin.common.util.ObjectUtils;
import com.bincloud.vue.admin.model.dto.ResourceDTO;
import com.bincloud.vue.admin.model.dto.UserDTO;
import com.bincloud.vue.admin.web.bo.VueAdminUserDetails;
import com.bincloud.vue.admin.web.service.api.UserService;
import com.bincloud.vue.admin.web.util.security.VueAdminUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;


/**
 * 用户数据操作接口实现
 * @author bincloud, mvpzhou
 */
@Service
@Slf4j
public class VueAdminUserDetailsServiceImpl implements VueAdminUserDetailsService {
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取用户信息
        UserDTO user = userService.getUserDTO(username);
        if (ObjectUtils.isNull(user)) {
            throw new BaseException(CodeMsg.UNAUTHORIZED);
        }
        if (!user.isAccountNonExpired()) {
            throw new BaseException(CodeMsg.ACCOUNT_EXPIRED);
        }
        if (!user.isAccountNonLocked()) {
            throw new BaseException(CodeMsg.ACCOUNT_LOCKED);
        }
        if (!user.isCredentialsNonExpired()) {
            throw new BaseException(CodeMsg.CREDENTIALS_EXPIRED);
        }
        if (!user.isEnabled()) {
            throw new BaseException(CodeMsg.ACCOUNT_DISABLED);
        }
        // 获取资源信息列表
        Set<ResourceDTO> resSet = userService.getResourceSets(username);
        return new VueAdminUserDetails(user, resSet);
    }
}
